import json
import copy
from copy import deepcopy
from flask import Blueprint, request, jsonify
from controllers.common import *
from controllers.db import *

strongest_sheriff_project_v2_api = Blueprint('strongest_sheriff_project_v2_api', __name__)
strongest_sheriff_project_v2_down_api = Blueprint('strongest_sheriff_project_v2_down_api', __name__)


def get_doc_file(field):
    with open(GLOBAL_PATH + 'operation_event_english.json', encoding='utf8') as f:
        data = json.load(f)
    if field in data:
        return data[field]
    else:
        return {}


@strongest_sheriff_project_v2_api.route('/strongest_sheriff_project_v2', methods=['POST'])
def strongest_sheriff_project_v2():
    params = json.loads(request.data)
    _action = params['action']
    _project = params['project']
    result_data = {'status': 200, 'data': {'msg': '', 'ret': 0, 'type': 'success', 'env': EVN, 'item': ''}}
    if _action == 'view':
        query = StrongestSheriffProjectV2.query.order_by('project').all()
        result = []
        for q in query:

            localization = json.loads(q.localization)
            if "1" in localization:
                title = localization["1"]["title"]
            else:
                title = ''

            tmp = {
                "project": int(q.project),
                'title': title,
                'remark': q.remark
            }
            result.append(tmp)
        result_data['data']['item'] = result
    elif _action == 'detail':
        query = StrongestSheriffProjectV2.query.filter_by(project=_project).first()
        basic = json.loads(query.basic)
        if 'calendar_reward' not in basic:
            basic['calendar_reward'] = []
        if 'doc_id' not in basic:
            basic['doc_id'] = int(_project)
        basic['doc_id_switch'] = False

        tmp = {
            "project": int(query.project),
            'basic': basic,
            'reward': json.loads(query.reward),
            'sub': json.loads(query.sub)
        }
        result_data['data']['item'] = tmp
    elif _action == 'detailSub':
        query = StrongestSheriffProjectV2Sub.query.filter_by(project=_project).first()
        # 20221115 子活动 title 默认为1
        basic = json.loads(query.basic)
        if 'sub_title' not in basic:
            basic['sub_title'] = 1
        tmp = {
            "project": int(query.project),
            'basic': basic,
            'reward': json.loads(query.reward),
        }
        result_data['data']['item'] = tmp
    
    elif _action == 'addStage':
        _calc_score = []
        with open(STATIC_PATH + 'strongest_sheriff_task_pool.json', encoding='UTF-8') as f:
            data = json.load(f)
            for i in data:
                _calc_score.append(i['idx'])
        _default_localization = {}
        for i in range(1, 21 + 1):
            _default_localization[str(i)] = {
                "title": "sub default title",
                "info": "sub default info",
                "content": "sub default content",
                "help_info": "sub default help_info"
            }
        new_sub_data = StrongestSheriffProjectV2Sub(
            basic=json.dumps({"event_ui":1015,"calc_score":_calc_score,"rank_limit":0,"doc_id": 1,"stage_type": 14}),
            localization=json.dumps(_default_localization),
            reward=json.dumps({"goal_reward":[]})
        )
        db.session.add(new_sub_data)
        db.session.commit()
        new_sub_id = new_sub_data.project
        if new_sub_id is None:
            result_data['status'] = 500
            result_data['data']['msg'] = "添加阶段失败：new stage id is None"
        else:
            strongest_sheriff_project_v2_data = StrongestSheriffProjectV2.query.filter_by(project=_project).first()
            _sub = json.loads(strongest_sheriff_project_v2_data.sub)
            _sub.append(new_sub_id)
            StrongestSheriffProjectV2.query.filter_by(project=_project).update({
                'sub': json.dumps(_sub)
            })
            result_data['data']['item'] = new_sub_id

    elif _action == 'cloneSub':
        sub_project = params['sub_project']
        node = StrongestSheriffProjectV2.query.filter_by(project=_project).first()
        sub_node = StrongestSheriffProjectV2Sub.query.filter_by(project=sub_project).first()
        new_sub_node = StrongestSheriffProjectV2Sub(
            basic=sub_node.basic,
            localization=sub_node.localization,
            reward=sub_node.reward
        )
        db.session.add(new_sub_node)
        db.session.commit()
        new_sub_id = new_sub_node.project
        if new_sub_id is None:
            result_data['status'] = 500
            result_data['data']['msg'] = "添加阶段失败：new stage id is None"
        else:
            node_sub = json.loads(node.sub)
            node_sub.append(new_sub_id)
            node.sub = json.dumps(node_sub)
            db.session.commit()
            result_data['data']['item'] = new_sub_id
    
    elif _action == 'deleteStage':
        _stage = params['stage']
        print(_stage)
        strongest_sheriff_project_v2_data = StrongestSheriffProjectV2.query.filter_by(project=_project).first()
        _sub = json.loads(strongest_sheriff_project_v2_data.sub)
        for i in range(0, len(_sub)):
            if _sub[i] == _stage:
                del _sub[i]
                break
        StrongestSheriffProjectV2.query.filter_by(project=_project).update({
            'sub': json.dumps(_sub)
        })
        result_data['data']['msg'] = "删除成功"
    elif _action == 'update_part':
        _data = params['data']
        _part = params['part']
        '''daily_deals_event_project_data = DailyDealsEventProject.query.filter_by(project=_project).first()
        reward = json.loads(daily_deals_event_project_data.reward)'''
        if _part == 'basic':
            StrongestSheriffProjectV2.query.filter_by(project=_project).update({
                'basic': json.dumps(_data)
            })
        elif _part == 'goal_reward':  # TODO
            new_personal_event_project_v2_data = NewPersonalEventProjectV2.query.filter_by(project=_project).first()
            reward = json.loads(new_personal_event_project_v2_data.reward)
            reward["goal_reward"] = _data
            NewPersonalEventProjectV2.query.filter_by(project=_project).update({
                'reward': json.dumps(reward)
            })
        elif _part == 'rank_reward':
            new_strongest_sheriff_project_v2_data = StrongestSheriffProjectV2.query.filter_by(project=_project).first()
            reward = json.loads(new_strongest_sheriff_project_v2_data.reward)
            reward["rank_reward"] = _data
            StrongestSheriffProjectV2.query.filter_by(project=_project).update({
                'reward': json.dumps(reward)
            })
        elif _part == 'sub_rank_reward':
            new_strongest_sheriff_project_v2_data = StrongestSheriffProjectV2.query.filter_by(project=_project).first()
            reward = json.loads(new_strongest_sheriff_project_v2_data.reward)
            reward["sub_rank_reward"] = _data
            StrongestSheriffProjectV2.query.filter_by(project=_project).update({
                'reward': json.dumps(reward)
            })
        elif _part == 'sub':
            new_sub_data = StrongestSheriffProjectV2Sub.query.filter_by(project=_data['project']).first()
            _basic = json.loads(new_sub_data.basic)
            _reward = json.loads(new_sub_data.reward)
            _basic['event_ui'] = _data['event_ui']
            _basic['rank_limit'] = _data['rank_limit']
            _basic['doc_id'] = _data['doc_id']
            _basic['stage_type'] = _data['stage_type']
            _basic['calc_score'] = _data['calc_score']
            _reward['goal_reward'] = _data['reward']
            _basic['sub_title'] = _data['sub_title']
            StrongestSheriffProjectV2Sub.query.filter_by(project=_data['project']).update({
                'basic': json.dumps(_basic),
                'reward': json.dumps(_reward)
            })
        db.session.commit()
        result_data['data']['msg'] = "更新成功"
    elif _action == 'remark':
        newRemark = params['remark']
        StrongestSheriffProjectV2.query.filter_by(project=_project).update({'remark': newRemark})
        db.session.commit()
        result_data['data']['msg'] = "Remark 更新成功"
    elif _action == 'clone':  # 克隆方案
        strongest_sheriff_project_v2_data = StrongestSheriffProjectV2.query.filter_by(project=_project).first()

        _sub_list = json.loads(strongest_sheriff_project_v2_data.sub)
        _replace_sub_list = []
        for i in _sub_list:
            strongest_sheriff_sub_project_v2_data = StrongestSheriffProjectV2Sub.query.filter_by(project=i).first()
            new_sub_project_data = StrongestSheriffProjectV2Sub(
                basic=strongest_sheriff_sub_project_v2_data.basic,
                localization=strongest_sheriff_sub_project_v2_data.localization,
                reward=strongest_sheriff_sub_project_v2_data.reward
            )
            db.session.add(new_sub_project_data)
            db.session.commit()
            new_sub_project_id = new_sub_project_data.project
            _replace_sub_list.append(new_sub_project_id)

        new_project_data = StrongestSheriffProjectV2(
            basic=strongest_sheriff_project_v2_data.basic,
            localization=strongest_sheriff_project_v2_data.localization,
            reward=strongest_sheriff_project_v2_data.reward,
            sub=json.dumps(_replace_sub_list),
            remark=strongest_sheriff_project_v2_data.remark
        )
        db.session.add(new_project_data)
        db.session.commit()
        new_project_id = new_project_data.project
        if new_project_id is None:
            result_data['status'] = 500
            result_data['data']['msg'] = "克隆失败：id is None"
        else:
            result_data['data']['msg'] = "克隆成功"
    elif _action == 'delete':
        strongest_sheriff_project_v2_data = StrongestSheriffProjectV2.query.filter_by(project=_project).first()
        db.session.delete(strongest_sheriff_project_v2_data)
        db.session.commit()
        strongest_sheriff_project_v2_data = StrongestSheriffProjectV2.query.filter_by(project=_project).first()
        if strongest_sheriff_project_v2_data is not None:
            result_data['status'] = 500
            result_data['data']['msg'] = "删除失败：id is not None"
        else:
            result_data['data']['msg'] = "删除成功"
    elif _action == 'score_list':
        with open(STATIC_PATH + 'strongest_sheriff_task_pool.json', encoding='UTF-8') as f:
            data = json.load(f)
            _result = []
            for i in data:
                _condition = '无条件'
                if len(i['show']) > 0:
                    if i['show'][0]['type'] == 1:
                        _condition = '满研究'
                _result.append({
                    "value": i['idx'],
                    "label": str(i['idx']) + '-' + i['label'] + '-' + _condition
                })
            return json.dumps(_result)
    elif _action == 'sub_doc_id_list':
        with open(GLOBAL_PATH + 'document_english.json', encoding='UTF-8') as f:
            data = json.load(f)
            _result = []

            for i in range(1, len(data['doc_stage_goal']) + 1):
                if str(i) in data['doc_stage_goal']:
                    _result.append({
                        "value": i,
                        "label": str(i) + ' - ' + data['doc_stage_goal'][str(i)]["name"]
                    })
            return json.dumps(_result)
    elif _action == 'doc_id_list':
        doc_file_data = get_doc_file('master_event')
        result = []
        for i in doc_file_data:
            result.append({
                'value': int(i),
                'label': f'{i} - {doc_file_data[i]["title"]}'
            })
        return json.dumps(result)
    elif _action == 'sub_title_doc_id_list':
        doc_file_data = get_doc_file('master_event_stage')
        result = []
        for i in doc_file_data:
            result.append({
                'value': int(i),
                'label': f'{i} - {doc_file_data[i]["title"]}'
            })
        return json.dumps(result)
    return jsonify(result_data)


@strongest_sheriff_project_v2_down_api.route('/strongest_sheriff_project_v2_down/<int:is_push>', methods=['GET', 'POST'])
def strongest_sheriff_project_v2_down(is_push):
    def get_reward_info(r):
        t = {"a": [r['type'], r['id'], r['num']]}
        return t
    def get_reward_list(a):
        tmp_reward = []
        for i in range(0, len(a)):
            for j in range(0, len(a[i]['reward'])):
                tmp_reward.append(get_reward_info(a[i]['reward'][j]))
        return tmp_reward

    result = {}
    result_sub = {}

    query = StrongestSheriffProjectV2.query.order_by('project').all()

    for q in query:
        _project = str(q.project)
        basic = json.loads(q.basic)
        localization = json.loads(q.localization)
        reward_data = json.loads(q.reward)
        sub = json.loads(q.sub)
        if 'doc_id' in basic:
            _master_doc_id = basic['doc_id']
        else:
            _master_doc_id = 1

        _temp_rank = []
        for i in range(0, len(reward_data["rank_reward"])):
            if reward_data["rank_reward"][i]["from"] == reward_data["rank_reward"][i]["to"]:
                _doc_id = 94922
            else:
                _doc_id = 94923
            _temp_rank.append({
                "from": reward_data["rank_reward"][i]["from"],
                "to": reward_data["rank_reward"][i]["to"],
                "reward": RewardToTMysqlNew(reward_data["rank_reward"][i]["reward"]),
                "doc_id": _doc_id
            })
        _temp_sub_rank = []
        for i in range(0, len(reward_data["sub_rank_reward"])):
            if reward_data["sub_rank_reward"][i]["from"] == reward_data["sub_rank_reward"][i]["to"]:
                _doc_id = 94924
            else:
                _doc_id = 94925
            _temp_sub_rank.append({
                "from": reward_data["sub_rank_reward"][i]["from"],
                "to": reward_data["sub_rank_reward"][i]["to"],
                "reward": RewardToTMysqlNew(reward_data["sub_rank_reward"][i]["reward"]),
                "doc_id": _doc_id
            })

        sub_rank_limit = []
        sub_rank_reward = []

        if '_tag' in basic:
            _tag = basic['_tag']
            del basic['_tag']
        else:
            _tag = []

        for i in sub:
            sub_rank_reward.append({
                "user": _temp_sub_rank
            })
            sub_data = StrongestSheriffProjectV2Sub.query.filter_by(project=i).first()
            _project_sub = str(sub_data.project)
            basic_sub = json.loads(sub_data.basic)

            localization_sub = json.loads(sub_data.localization)
            for i in localization_sub:
                if i in localization:
                    localization_sub[i]['m_title'] = localization[i]['title']

            reward_data_sub = json.loads(sub_data.reward)

            _calc_score_sub = []
            with open(STATIC_PATH + 'strongest_sheriff_task_pool.json', encoding='UTF-8') as f:
                data = json.load(f)
                for z in basic_sub['calc_score']:
                    for j in data:
                        if j['idx'] == z:
                            temp = copy.deepcopy(j)
                            if 'idx' in temp:
                                del temp['idx']
                            if 'label' in temp:
                                del temp['label']
                            _calc_score_sub.append(temp)

            _temp_goal_sub = []
            for i in range(0, len(reward_data_sub["goal_reward"])):
                _temp_goal_sub.append({
                    "from": 1,
                    "to": reward_data_sub["goal_reward"][i]["to"],
                    "reward": RewardToTMysqlNew(reward_data_sub["goal_reward"][i]["reward"]),
                    "doc_id": basic_sub['doc_id']
                })

            # 20221115 文案分离
            if 'sub_title' in basic_sub:
                sub_title = basic_sub['sub_title']
            else:
                sub_title = 1

            tmp_sub = {
                '_tag': _tag,
                "basic": {
                    "event_ui": basic_sub['event_ui']
                },
                "localization_str": localization_sub,
                "localization_doc": {
                    'title': sub_title,
                    'info': sub_title,
                    'content': sub_title,
                    'help_info': sub_title,
                    'm_title': _master_doc_id,
                },
                "calc_score": {
                    "score_type_list": _calc_score_sub
                },
                "castle_lv": basic["castle_lv"],
                "reward": {
                    "goal_reward": {
                        "user": _temp_goal_sub
                    },
                    "rank_reward": {
                        "user": _temp_sub_rank
                    }
                },
                "extern0": {
                    "rank_limit": basic_sub["rank_limit"]
                },
                "extern1": {},
                "stage_type": basic_sub["stage_type"]
            }
            result_sub[_project_sub] = tmp_sub
            sub_rank_limit.append(basic_sub["rank_limit"])

        if 'calendar_reward' in basic:
            calendar_reward = RewardToTMysqlNew(basic['calendar_reward'])
        else:
            calendar_reward = []

        # if 'calendar_doc_id' in basic:
        #     _calendar_doc_id = basic['calendar_doc_id']
        # else:
        #     _calendar_doc_id = 1
        # 20221128优化 将日历的doc_id改为与活动doc_id一致
        tmp = {
            '_tag': _tag,
            'calendar_conf': {
                'event_type': 98,
                'event_ui': basic['event_ui'],
                'order': 1,
                'jump': 1,
                'localization': {
                    'title': _master_doc_id,
                    'info': _master_doc_id
                },
                'reward': calendar_reward,
                'show_type': 0
            },
            "basic": {
                "event_ui": basic['event_ui']
            },
            "localization_str": localization,
            "localization_doc": {
                'title': _master_doc_id,
                'info': _master_doc_id,
                'content': _master_doc_id,
                'help_info': _master_doc_id,
            },
            "calc_score": {
                "score_type_list": [
                    {
                        "type": 100002,
                        "id_list": [-1],
                        "lv_list": [-1],
                        "id_class": 0,
                        "doc_id": -1,  # TODO
                        "num_unit": 1,
                        "show": [],
                        "class": 1,
                        "num": 1,
                        "score": 1,
                        "task_id": 0,
                        "target": 0
                    }
                ]
            },
            "castle_lv": basic["castle_lv"],
            "reward": {
                "rank_reward": {
                    "user": _temp_rank
                }
            },
            "extern0": {
                "sub_rank_reward": sub_rank_reward,
                "sub_rank_limit": sub_rank_limit,
                "rank_limit": basic["rank_limit"]
            },
            "extern1": {},
            "remark": q.remark,
            "sub_pid_list": q.sub
        }
        result[_project] = tmp

    if is_push == 0:
        response = DownLoad('strongest_sheriff_project_v2', result, 0)
    if is_push == 2:
        response = DownLoad('strongest_sheriff_sub_project_v2', result_sub, 0)
    if is_push == 1:
        r1 = DownLoad('strongest_sheriff_project_v2', result, 1)
        r2 = DownLoad('strongest_sheriff_sub_project_v2', result_sub, 1)
        if r1 and r2:
            return jsonify({"msg": "发布成功", "ret": 1})
        else:
            return False
    return response
